/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ViewTimeSlot.java
 *
 * Created on Jul 25, 2011, 4:03:42 PM
 */
package admin;

import generalCode.Connectionsql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Hoai An
 */
public class ViewAppointmentForm extends javax.swing.JFrame {

    private boolean isUpdate = false;
    private boolean isDelete = false;
    private ArrayList<AppointmentDTO> listAppointment = new ArrayList<AppointmentDTO>();
    Vector<String> columnNames;

    {
        columnNames = new Vector<String>();
        columnNames.add("ID");
        columnNames.add("Patient ID");
        columnNames.add("Date");
        columnNames.add("Time");
        columnNames.add("Time Slot");
        columnNames.add("Reson for Visit");
        columnNames.add("EmployeeID");
    }

    /** Creates new form ViewTimeSlot */
    public ViewAppointmentForm() {
        initComponents();
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        this.setTitle("View All Appointment");
        initData();

        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception ex) {
            Logger.getLogger(ViewAppointmentForm.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btgstatus = new javax.swing.ButtonGroup();
        pnContent = new javax.swing.JPanel();
        pnBottom = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbApp = new javax.swing.JTable();
        jLabel9 = new javax.swing.JLabel();
        cbxSeach = new javax.swing.JComboBox();
        tfSeach = new javax.swing.JTextField();
        btSeach = new javax.swing.JButton();
        pnTop = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        tfAppointmentID = new javax.swing.JTextField();
        tfPatientID = new javax.swing.JTextField();
        tfEmployeeID = new javax.swing.JTextField();
        tfDate = new javax.swing.JTextField();
        tfTime = new javax.swing.JTextField();
        tfTimeSlot = new javax.swing.JTextField();
        tfReason = new javax.swing.JTextField();
        btAdd = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();
        btReset = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        pnContent.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Edit Appointment", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        pnBottom.setLayout(null);

        tbApp.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "ID", "PatientID", "Date", "Time", "Timew Slot", "ReasonForVistting", "EmployeeID"
            }
        ));
        tbApp.setColumnSelectionAllowed(true);
        tbApp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbAppMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbApp);
        tbApp.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        pnBottom.add(jScrollPane1);
        jScrollPane1.setBounds(0, 80, 810, 190);

        jLabel9.setText("Seach with:");
        pnBottom.add(jLabel9);
        jLabel9.setBounds(40, 30, 56, 14);

        cbxSeach.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "      ID", "       PatientID", "      Appointment Name", "       Date" }));
        pnBottom.add(cbxSeach);
        cbxSeach.setBounds(110, 30, 134, 20);
        pnBottom.add(tfSeach);
        tfSeach.setBounds(260, 30, 190, 20);

        btSeach.setText("Seach");
        btSeach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSeachActionPerformed(evt);
            }
        });
        pnBottom.add(btSeach);
        btSeach.setBounds(470, 30, 61, 23);

        pnTop.setLayout(null);

        jLabel1.setText("AppointmentID:");
        pnTop.add(jLabel1);
        jLabel1.setBounds(40, 60, 100, 14);

        jLabel2.setText("PartientID:");
        pnTop.add(jLabel2);
        jLabel2.setBounds(60, 90, 80, 14);

        jLabel3.setText("Date: ");
        pnTop.add(jLabel3);
        jLabel3.setBounds(60, 150, 60, 14);

        jLabel4.setText("Time: ");
        pnTop.add(jLabel4);
        jLabel4.setBounds(450, 80, 50, 20);

        jLabel5.setText("Reason:");
        pnTop.add(jLabel5);
        jLabel5.setBounds(440, 150, 70, 14);

        jLabel7.setText("Time Slot:    ");
        pnTop.add(jLabel7);
        jLabel7.setBounds(430, 110, 70, 14);

        jLabel8.setText("EmployeeID: ");
        pnTop.add(jLabel8);
        jLabel8.setBounds(50, 120, 90, 14);

        tfAppointmentID.setEditable(false);
        pnTop.add(tfAppointmentID);
        tfAppointmentID.setBounds(170, 60, 210, 20);
        pnTop.add(tfPatientID);
        tfPatientID.setBounds(170, 90, 210, 20);

        tfEmployeeID.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfEmployeeIDActionPerformed(evt);
            }
        });
        pnTop.add(tfEmployeeID);
        tfEmployeeID.setBounds(170, 120, 210, 20);
        pnTop.add(tfDate);
        tfDate.setBounds(170, 150, 210, 20);
        pnTop.add(tfTime);
        tfTime.setBounds(510, 70, 230, 20);
        pnTop.add(tfTimeSlot);
        tfTimeSlot.setBounds(510, 110, 230, 20);
        pnTop.add(tfReason);
        tfReason.setBounds(510, 150, 230, 20);

        btAdd.setText("Add");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });
        pnTop.add(btAdd);
        btAdd.setBounds(270, 200, 90, 23);

        btDelete.setText("Delete");
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteActionPerformed(evt);
            }
        });
        pnTop.add(btDelete);
        btDelete.setBounds(370, 200, 90, 23);

        btReset.setText("Reset");
        btReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btResetActionPerformed(evt);
            }
        });
        pnTop.add(btReset);
        btReset.setBounds(480, 200, 90, 23);

        javax.swing.GroupLayout pnContentLayout = new javax.swing.GroupLayout(pnContent);
        pnContent.setLayout(pnContentLayout);
        pnContentLayout.setHorizontalGroup(
            pnContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnContentLayout.createSequentialGroup()
                .addGroup(pnContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnContentLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(pnTop, javax.swing.GroupLayout.DEFAULT_SIZE, 802, Short.MAX_VALUE))
                    .addComponent(pnBottom, javax.swing.GroupLayout.PREFERRED_SIZE, 812, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        pnContentLayout.setVerticalGroup(
            pnContentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnContentLayout.createSequentialGroup()
                .addComponent(pnTop, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(pnBottom, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnContent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnContent, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btResetActionPerformed
        resetForm();
}//GEN-LAST:event_btResetActionPerformed

    private void btDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteActionPerformed
        String IdApp = this.tfAppointmentID.getText();
        if (!isDelete) {
            JOptionPane.showMessageDialog(this, "Please, choose Appointment for delete!");
        } else {
            int response = JOptionPane.showConfirmDialog(null, "Are you sure delete it?", "Confirm",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.YES_OPTION) {
                deleteApp(IdApp);
            }
        }
}//GEN-LAST:event_btDeleteActionPerformed

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        String idApp = this.tfAppointmentID.getText();
        String idPat = this.tfPatientID.getText();
        String idEmp = this.tfEmployeeID.getText();
        String date = this.tfDate.getText();
        String time = this.tfTime.getText();
        String timeSlot = this.tfTimeSlot.getText();
        String reason = this.tfReason.getText();
        if (idPat.equals("") || idEmp.equals("") || date.equals("") || time.equals("")) {
            JOptionPane.showMessageDialog(this, "Please! Complete information required!");
        } else {
            if (!isUpdate) {
                addAppointment(idPat, idEmp, date, time, timeSlot, reason);
            } else {
                updatetAppointment(idApp, idPat, idEmp, date, time, timeSlot, reason);
                this.resetForm();
                this.isUpdate = false;
                this.btAdd.setText("Add");
            }
        }
}//GEN-LAST:event_btAddActionPerformed

    private void tfEmployeeIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfEmployeeIDActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_tfEmployeeIDActionPerformed

    private void tbAppMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbAppMouseClicked
        showInfo();
        isDelete = true;
        isUpdate = true;
    }//GEN-LAST:event_tbAppMouseClicked

    private void btSeachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSeachActionPerformed
        String inputSeach = this.tfSeach.getText();
        int isSelected = this.cbxSeach.getSelectedIndex();
        if (inputSeach.equals("")) {
            JOptionPane.showMessageDialog(this, "Input seacch is not blank! Please try again!");
        } else {
            Seach(inputSeach, isSelected);
        }
}//GEN-LAST:event_btSeachActionPerformed
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new ViewTimeSlot().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btDelete;
    private javax.swing.JButton btReset;
    private javax.swing.JButton btSeach;
    private javax.swing.ButtonGroup btgstatus;
    private javax.swing.JComboBox cbxSeach;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pnBottom;
    private javax.swing.JPanel pnContent;
    private javax.swing.JPanel pnTop;
    private javax.swing.JTable tbApp;
    private javax.swing.JTextField tfAppointmentID;
    private javax.swing.JTextField tfDate;
    private javax.swing.JTextField tfEmployeeID;
    private javax.swing.JTextField tfPatientID;
    private javax.swing.JTextField tfReason;
    private javax.swing.JTextField tfSeach;
    private javax.swing.JTextField tfTime;
    private javax.swing.JTextField tfTimeSlot;
    // End of variables declaration//GEN-END:variables

    private void initData() {
        initTable(null);
    }

    private void initTable(String sql) {
        try {
            listAppointment = new ArrayList<AppointmentDTO>();
            this.tbApp.removeAll();
            //load database
            Connectionsql db = Connectionsql.newInstance();
            if (sql == null) {
                sql = "SELECT * FROM Appointment";
            }
            ResultSet rs = db.query(sql);
            while (rs.next()) {
                listAppointment.add(new AppointmentDTO(rs.getInt("appointmentid"), rs.getInt("patientid"),
                        rs.getString("date"), rs.getString("time"),
                        rs.getString("timeslots"), rs.getString("reasonforvisiting"), rs.getInt("employeeid")));
            }
            db.closeConn();
            //show table
            Vector<Vector<String>> data = new Vector<Vector<String>>();
            for (int i = 0; i < listAppointment.size(); i++) {
                Vector<String> v = new Vector<String>();
                v.add(listAppointment.get(i).getAppid() + "");
                v.add(listAppointment.get(i).getPatientid() + "");
                v.add(listAppointment.get(i).getDate());
                v.add(listAppointment.get(i).getTime());
                v.add(listAppointment.get(i).getTimeSlot());
                v.add(listAppointment.get(i).getReason());
                v.add(listAppointment.get(i).getEmpid() + "");

                data.add(v);

            }

            tbApp.setModel(new DefaultTableModel(data, columnNames));
        } catch (SQLException ex) {
            Logger.getLogger(ViewAppointmentForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void resetForm() {
        this.tfAppointmentID.setText("");
        this.tfPatientID.setText("");
        this.tfEmployeeID.setText("");
        this.tfDate.setText("");
        this.tfTime.setText("");
        this.tfReason.setText("");
        this.tfTimeSlot.setText("");
        this.btAdd.setText("Add");
        isUpdate = false;
        isDelete = false;
    }

    private void addAppointment(String idPat, String idEmp, String date, String time, String timeSlot, String reason) {
        Connectionsql db = Connectionsql.newInstance();
        if (validateInput()) {
            try {
                String sql = "insert into Appointment(PatientID, [Date], [Time], TimeSlots,ReasonForVisiting, EmployeeID) values('" + idPat
                        + "', '" + date
                        + "', '" + time
                        + "', '" + timeSlot
                        + "', '" + reason
                        + "', '" + idEmp
                        + "');";
                System.out.println(sql);
                if (db.update(sql)) {
                    JOptionPane.showMessageDialog(this, "Add new Appointment successfully!");
                    initData();
                }
                db.closeConn();
            } catch (SQLException ex) {
                Logger.getLogger(ViewAppointmentForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void deleteApp(String IdApp) {
            try {
                String sql = "delete Appointment where Appointmentid=?;";
                Object[] arr = new Object[]{IdApp};
                Connectionsql conn = Connectionsql.newInstance();
                if (conn.updateWithParam(sql, arr)) {
                    JOptionPane.showMessageDialog(this, "Delete Appointment successfully!");
                    initData();
                    conn.closeConn();
                }
            } catch (SQLException ex) {
                Logger.getLogger(ManagerUserForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    private boolean validateInput() {
        if (tfPatientID.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in Partientid!");
            return false;
        } else if (tfEmployeeID.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in Employeeid!");
            return false;
        } else if (tfDate.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in date!");
            return false;
        } else if (tfTime.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in time!");
            return false;
        } else if (tfTimeSlot.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in time slot!");
            return false;
        } else if (tfReason.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please! Fill in reson for visit!");
            return false;
        }
        return true;
    }

    private void updatetAppointment(String idApp, String idPat, String idEmp, String date, String time, String timeSlot, String reason) {
        Connectionsql db = Connectionsql.newInstance();
        if (validateInput()) {
            try {
                String sql = "update appointment set PatientID=?, [Date]=?, [Time]=?, TimeSlots=?, ReasonForVisiting=?, EmployeeID=? where Appointmentid = ?";
                Object[] arr = new Object[]{idPat, date, time, timeSlot, reason, idEmp, idApp};
                System.out.println(sql);
                if (db.updateWithParam(sql, arr)) {
                    JOptionPane.showMessageDialog(this, "Update Appointment successfully!");
                    initData();
                }
                db.closeConn();
            } catch (SQLException ex) {
                Logger.getLogger(PatientForm.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }
        }
    }

    private void showInfo() {
        this.btAdd.setText("Update");
        int selectedRow = -1;
        selectedRow = tbApp.getSelectedRow();
        if (selectedRow != -1) {
            tfAppointmentID.setText(listAppointment.get(selectedRow).getAppid() + "");
            tfPatientID.setText(listAppointment.get(selectedRow).getPatientid() + "");
            tfEmployeeID.setText(listAppointment.get(selectedRow).getEmpid() + "");
            tfDate.setText(listAppointment.get(selectedRow).getDate());
            tfTime.setText(listAppointment.get(selectedRow).getTime());
            tfTimeSlot.setText(listAppointment.get(selectedRow).getTimeSlot());
            tfReason.setText(listAppointment.get(selectedRow).getReason());
        }
    }

    private void Seach(String inputSeach, int isSelected) {
        String sql = "";
        if (isSelected == 0) {
            sql = "select * from Appointment where Appointmentid like " + inputSeach + " order by Appointmentid";
        } else if (isSelected == 1) {
            sql = "select * from Appointment where PatientID like '%" + inputSeach + "%' order by Appointmentid";
        }
        else if (isSelected == 2) {
            sql = "select * from Appointment where Appointmentname like '%" + inputSeach + "%' order by Appointmentid";
        } else if (isSelected == 3) {
            sql = "select * from Appointment where date like '%" + inputSeach + "%' order by Appointmentid";
        }
        initTable(sql);
    }
}
